import classNames from "classnames";
import "./index.scss";
import { Fragment } from "react/jsx-runtime";
import { useCallback, useEffect, useState } from "react";
import powerSet from "../../../../utils/powerSet";
const spliter = "☆";

// 创建路径字典有效的
function getPathMap(skus: any) {
  const pathMap: any = {};
  const validSku = skus.filter((item: any) => item.inventory > 0);
  validSku.forEach((ele: any) => {
    const valueArr = ele.specs.map((sub: any) => sub.valueName);
    const powerSetArr = powerSet(valueArr);
    powerSetArr.forEach((set: any) => {
      const key: any = set.join(spliter);
      if (pathMap[key]) {
        // 已经有key往数组追加
        pathMap[key].push(ele.id);
      } else {
        // 没有key设置一个数组
        pathMap[key] = [ele.id];
      }
    });
  });
  return pathMap;
}
// 初始化状态更新
function updateStatus(specs: any, pathMap: any) {
  specs.forEach((ele: any, i: number) => {
    const selectValues = selectedValues(specs);
    ele.values.forEach((item: any) => {
      if (item.selected) return;
      selectValues[i] = item.name;
      const key = selectValues.filter((v) => v).join(spliter);
      item.disabled = !pathMap[key];
    });
  });
}
// 选中值[黑色，undefined，undefined]
function selectedValues(specs: any) {
  const arr: any[] = [];
  specs.forEach((ele: any) => {
    const selected = ele.values.find((sub: any) => sub.selected);
    if (selected) {
      arr.push(selected.name);
    } else {
      arr.push(undefined);
    }
  });
  return arr;
}
function GoodsSku({
  goods,
  skuId,
  emitSku,
}: {
  goods: any;
  skuId?: string;
  emitSku: (val?: any) => void;
}) {
  const [tempGoods, setTempGoods] = useState(() => goods);
  const pathMap = getPathMap(goods.skus); //路径字典

  // 初始化选中状态
  function initDefaultSelected(goods: any, skuId: string) {
    const newGoods = { ...goods }; // 复制 goods，确保不直接修改原对象
    const sku = newGoods.skus.find((item: any) => item.id === skuId);
    newGoods.specs.forEach((ele: any, i: number) => {
      const val = ele.values.find(
        (item: any) => item.name === sku.specs[i].valueName
      );
      if (val) {
        val.selected = true;
      }
    });
    // 更新状态，触发视图更新
    setTempGoods(newGoods);
  }

  useEffect(() => {
    if (skuId) {
      initDefaultSelected(goods, skuId);
    }
  }, [skuId, goods]);

  const changeSku = function (item: any, val: any) {
    if (val.disabled) return;

    // 复制当前 goods 状态，避免直接修改原对象
    const newGoods = { ...tempGoods };

    if (val.selected) {
      val.selected = false;
    } else {
      // 找到对应的 item 和 value
      item.values.forEach((v: any) => {
        v.selected = false; // 先清空所有选中状态
      });
      val.selected = true; // 设置当前点击的值为选中状态
    }

    // 点击时更新状态并触发重新渲染
    updateStatus(goods.specs, pathMap);
    setTempGoods(newGoods); // 更新 tempGoods
    // 发送父组件信息
    // 1.完整的sku信息
    const selectVal = selectedValues(goods.specs).filter((v) => v);
    if (goods.specs.length === selectVal.length) {
      const validSkuId = pathMap[selectVal.join(spliter)]; //选择完整的skuid
      const skus = goods.skus.find((item: any) => item.id === validSkuId[0]);

      emitSku({
        skuId: skus.id,
        oldPrice: skus.oldPrice,
        price: skus.price,
        inventory: skus.inventory,
        specsText: skus.specs
          .reduce((p: any, n: any) => `${p}${n.name}:${n.valueName}`, "")
          .replace(" ", ""),
      });
    } else {
      emitSku({});
    }
    // 2.不完整
  };
  // 初始化按钮状态
  updateStatus(goods.specs, pathMap);

  return (
    <div className="goods-sku">
      {tempGoods?.specs?.map((item: any) => (
        <dl key={item.id}>
          <dt>{item.name}</dt>
          <dd>
            {item.values.map((v: any) => (
              <Fragment key={v.name}>
                {v.picture ? (
                  <img
                    src={v.picture}
                    title={v.name}
                    className={classNames({
                      selected: v.selected,
                      disabled: v.disabled,
                    })}
                    onClick={() => changeSku(item, v)}
                  />
                ) : (
                  <span
                    className={classNames({
                      selected: v.selected,
                      disabled: v.disabled,
                    })}
                    onClick={() => changeSku(item, v)}
                  >
                    {v.name}
                  </span>
                )}
              </Fragment>
            ))}
          </dd>
        </dl>
      ))}
    </div>
  );
}
export default GoodsSku;
